<template>
  <div class="app-container">
    <el-form :inline="true" :model="formParams" ref="queryForm" class="demo-form-inline">
      <el-form-item label="任务名称">
        <el-input v-model="formParams.jobName" placeholder="请输入任务名称"></el-input>
      </el-form-item>
      <!-- <el-form-item label="任务组名">
        <el-input   v-model="formParams.jobGroup"  placeholder="请输入任务组名"  ></el-input>
      </el-form-item> -->
      <el-form-item label="任务状态">
        <el-select v-model="formParams.status" placeholder="请选择任务状态">
          <el-option label="停用" value="0"></el-option>
          <el-option label="启用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增 </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="updateBtn || tableData.length == 0" @click="handleUpdate(multipleSelection[0])">修改 </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="tableData.length < 1" @click="handleDelete(1, multipleSelection)">删除 </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :disabled="tableData.length < 1"
          @click="handleExport"
          >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-s-operation"
          size="mini"
          :disabled="tableData.length < 1"
          @click="handleLog"
          >日志
        </el-button>
      </el-col> -->
    </el-row>
    <!-- table -->
    <el-table v-loading="loading" element-loading-text="正在加载，请稍后" ref="multipleTable" :data="tableData" tooltip-effect="dark" max-height="600" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"> </el-table-column>
      <el-table-column type="index" :index="1" label="任务编号" width="90" align="center"> </el-table-column>
      <el-table-column prop="jobName" label="任务名称" align="center"> </el-table-column>
      <!-- <el-table-column prop="remarks" label="任务描述" align="center"> </el-table-column> -->
      <!-- <el-table-column prop="jobGroup" label="任务组名" align="center">
      </el-table-column> -->

      <el-table-column prop="invokeTarget" label="数据开发脚本" align="center" show-overflow-tooltip> </el-table-column>
      <el-table-column prop="cronExpression" label="调度策略" align="center" show-overflow-tooltip> </el-table-column>
      <!-- <el-table-column label="计划执行错误策略" width="140" align="center">
        <template slot-scope="scope">{{
          scope.row.misfirePolicy == '1'
            ? '立即执行'
            : scope.row.misfirePolicy == '2'
            ? '执行一次'
            : scope.row.misfirePolicy == '3'
            ? '放弃执行'
            : ''
        }}</template>
      </el-table-column> -->
      <!-- <el-table-column label="是否并发执行" width="120" align="center">
        <template slot-scope="scope">{{
          scope.row.concurrent == '0'
            ? '允许'
            : scope.row.concurrent == '1'
            ? '禁止'
            : ''
        }}</template>
      </el-table-column> -->
      <el-table-column label="状态" width="120" align="center">
        <template slot-scope="scope">
          <el-switch active-value="1" inactive-value="0" :value="scope.row.status" @change="handleSwitchChange(scope.row)"> </el-switch>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding" width="220px">
        <template slot-scope="scope">
          <el-button v-if="scope.row.examineStatus == '1'" size="mini" type="text" icon="el-icon-document-copy" @click="handle(scope.row)">申请 </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改 </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(2, scope.row)">删除 </el-button>
          <el-dropdown trigger="click" @command="(commandName) => handleCommand(commandName, scope.row)">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多 </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-caret-right" command="a">执行一次</el-dropdown-item>
              <el-dropdown-item icon="el-icon-view" command="b">任务详细</el-dropdown-item>
              <el-dropdown-item icon="el-icon-s-operation" command="c">调度日志</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="formParams.page" :limit.sync="formParams.limit" @pagination="getList" />

    <el-dialog v-if="open" :title="title" :visible.sync="open" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务名称" prop="jobName">
              <el-input v-model="form.jobName" placeholder="请输入任务名称" :disabled="disabled" />
            </el-form-item>
          </el-col>

          <!-- 任务描述 -->
          <el-col :span="12">
            <el-form-item label="任务描述" prop="remarks">
              <el-input type="textarea" :rows="2" v-model="form.remarks" placeholder="请输入任务描述" :disabled="disabled" />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="任务分组" prop="jobGroup">
              <el-input v-model="form.jobGroup" placeholder="请输入任务分组" />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-form-item label="数据开发脚本" prop="invokeTarget">
          <el-input v-model="form.invokeTarget" placeholder="请输入数据开发脚本" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="调度策略" prop="cronExpression">
          <el-input v-model="form.cronExpression" :disabled="disabled" placeholder="请输入调度策略" @focus="dialogCron = true" />
        </el-form-item>
        <!-- <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="执行策略" prop="misfirePolicy">
              <el-radio-group v-model="form.misfirePolicy">
                <el-radio-button label="1">立即执行</el-radio-button>
                <el-radio-button label="2">执行一次</el-radio-button>
                <el-radio-button label="3">放弃执行</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否并发" prop="concurrent">
              <el-radio-group v-model="form.concurrent" size="medium">
                <el-radio-button label="0">允许</el-radio-button>
                <el-radio-button label="1">禁止</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!disabled">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="生成执行表达式" :visible.sync="dialogCron" :append-to-body="true" :close-on-click-modal="false">
      <Crontab @fill="getStr" @hide="dialogCron = false"></Crontab>
    </el-dialog>
    <el-dialog title="调度日志" :visible.sync="openLog" :close-on-click-modal="false">
      <el-table v-loading="loadingLog" ref="multipleTable" :data="tableDataLog" tooltip-effect="dark" element-loading-text="正在加载，请稍后">
        <el-table-column type="selection" width="55" align="center"> </el-table-column>
        <!-- <el-table-column type="index" :index="1" label="任务编号" width="90" align="center"> </el-table-column> -->
        <el-table-column prop="jobName" label="任务名称" align="center"> </el-table-column>
        <el-table-column prop="jobGroup" label="任务组名" align="center" show-overflow-tooltip> </el-table-column>
        <el-table-column prop="invokeTarget" label="调用目标字符串" align="center" show-overflow-tooltip> </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0">执行成功</span>
            <span v-else-if="scope.row.status == 1">执行成功</span>
            <span v-else>执行失败</span>
          </template>
        </el-table-column>
        <el-table-column prop="jobMessage" label="日志信息" align="center" show-overflow-tooltip> </el-table-column>
        <el-table-column prop="exceptionInfo" label="异常信息" align="center" show-overflow-tooltip> </el-table-column>

        <el-table-column prop="createTime" label="创建时间" width="200" align="center" show-overflow-tooltip> </el-table-column>
      </el-table>
      <div slot="footer" style="padding: 1.25rem" class="dialog-footer">
        <pagination v-show="totalLog > 0" :total="totalLog" :page.sync="formLog.page" :limit.sync="formLog.limit" @pagination="getLogList" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import pagination from '@/components/Pagination'
import Crontab from '@/components/Crontab/index.vue'

import { getTableData, add, update, deleteData, statusUpdate, run, getTableDataLog, geusen } from '@/api/timedTask/index.js'
export default {
  name: 'SdssDatagovernanceFrontendIndex',
  components: {
    pagination,
    Crontab,
  },
  data() {
    return {
      loading: false,
      loadingLog: false,
      title: '',
      open: false,
      openLog: false,
      formParams: {
        page: 1,
        limit: 10,
        jobName: null,
        jobGroup: null,
        status: null,
      },
      formLog: {
        page: 1,
        limit: 10,
        jobId: null,
      },
      tableData: [],
      tableDataLog: [],
      multipleSelection: [],
      // 总条数
      total: 10,
      form: {},
      // 表单校验
      rules: {
        remarks: [{ required: true, message: '任务描述不能为空', trigger: 'blur' }],
        jobName: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
        invokeTarget: [{ required: true, message: '调用方法不能为空', trigger: 'blur' }],
        cronExpression: [
          {
            required: true,
            message: 'cron表达式不能为空',
            trigger: ['blur', 'change'],
          },
        ],
      },
      updateBtn: true,
      disabled: false,
      dialogCron: false,
    }
  },
  created() {
    this.getList()
  },
  mounted() {},

  methods: {
    getStr(str) {
      this.form.cronExpression = str
    },
    getList() {
      this.loading = true
      getTableData(this.formParams).then((response) => {
        console.log(response, '--->response')
        this.tableData = response.data.data
        this.total = response.data.total
        this.loading = false
      })
    },

    getLogList() {
      this.loadingLog = true
      getTableDataLog(this.formLog).then((response) => {
        console.log(response.data)
        this.tableDataLog = response.data.data.records
        this.totalLog = response.data.data.total
        this.loadingLog = false
      })
    },
    handle(item) {
      geusen({
        type: 1,
        dataId: item.id,
      }).then((res) => {
        if (res.data.code == 0) {
          this.$message.success(res.data.msg)
          this.getList()
        }
      })
    },
    handleSearch() {
      this.formParams.pageNum = 1
      this.getList()
    },
    handleReset() {
      this.formParams = {
        pageNum: 1,
        pageSize: 10,
        jobName: null,
        jobGroup: null,
        status: null,
      }
      this.handleSearch()
    },
    reset() {
      this.form = {
        id: null,
        jobName: null,
        jobGroup: null,
        invokeTarget: null,
        cronExpression: null,
        misfirePolicy: null,
        concurrent: null,
      }
      this.formParams = {
        pageNum: 1,
        pageSize: 10,
        jobName: null,
        jobGroup: null,
        status: null,
      }
    },
    handleAdd() {
      this.reset() //todo
      this.open = true
      this.title = '添加定时任务'
      this.disabled = false
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            update(this.form).then((res) => {
              console.log(res, '213123123')
              if (res.data.code == 200) {
                this.$message({
                  message: '修改成功',
                  type: 'success',
                })
                this.open = false
                this.getList()
              } else {
                this.$message({
                  message: res.data.msg || '修改失败',
                  type: 'error',
                })
                // this.getList()
              }
            })
          } else {
            console.log('111111111111111111111')
            add(this.form).then((res) => {
              // console.log(res, '==========>?')
              if (res.data.code == 200) {
                this.$message({
                  message: '新增成功',
                  type: 'success',
                })
                this.open = false
                this.getList()
              } else {
                this.$message({
                  message: res.data.msg || '新增失败',
                  type: 'error',
                })
              }
            })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    //修改
    handleUpdate(row) {
      if (row) {
        this.reset()
        this.title = '修改定时任务'
        this.open = true
        this.disabled = false

        this.form = {
          id: row.id,
          jobName: row.jobName,
          invokeTarget: row.invokeTarget,
          cronExpression: row.cronExpression,
          remarks: row.remarks,
        }
      } else return
    },
    //删除
    handleDelete(type, row) {
      const ids = []
      if (type == 1 && row.length > 0) {
        row.forEach((item) => {
          ids.push(item.id)
        })
      } else if (type == 2) {
        ids.push(row.id)
      } else {
        return this.$message({
          message: '请选择要删除的数据',
          type: 'warning',
        })
      }
      this.$confirm('是否确认删除该数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return deleteData(ids)
        })
        .then(() => {
          this.getList()
          this.$message({
            message: '删除成功',
            type: 'success',
          })
        })
        .catch((error) => {
          if (error && error !== 'cancel' && error !== 'escape key press') {
            console.error('删除操作遇到错误', error)
            this.$message({
              message: '删除失败',
              type: 'error',
            })
          }
        })
    },
    handleSelectionChange(val) {
      // console.log(val, '6666666666666')
      if (val.length == 1) {
        this.updateBtn = false
      } else {
        this.updateBtn = true
      }
      this.multipleSelection = val
    },
    handleCommand(command, row) {
      if (command == 'a') {
        this.$confirm('确定要执行吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(function () {
            return run(row)
          })
          .then((res) => {
            if (res.data.code == 200) {
              this.getList()
              this.$message({
                message: '执行成功',
                type: 'success',
              })
            } else {
              this.$message({
                message: res.data.msg,
                type: 'error',
              })
            }
          })
          .catch((error) => {
            if (error && error !== 'cancel' && error !== 'escape key press') {
              this.$message({
                message: '执行失败',
                type: 'error',
              })
            }
            this.getList()
          })
      } else if (command == 'b') {
        this.title = '查看定时任务'
        this.open = true
        this.form = {
          id: row.id,
          jobName: row.jobName,
          invokeTarget: row.invokeTarget,
          cronExpression: row.cronExpression,
          remarks: row.remarks,
        }
        this.disabled = true
      } else if (command == 'c') {
        this.openLog = true
        this.formLog.jobId = row.id
        this.getLogList()
      }
    },
    handleExport() {
      console.log('1')
    },
    handleLog() {
      console.log('2')
    },
    handleSwitchChange(row) {
      let status = row.status
      if (status == '0') {
        row.status = '1'
      } else row.status = '0'
      this.$confirm('确认要修改状态吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return statusUpdate(row)
        })
        .then(() => {
          this.getList()
          this.$message({
            message: '修改状态成功',
            type: 'success',
          })
        })
        .catch((error) => {
          if (error && error !== 'cancel' && error !== 'escape key press') {
            console.error('删除操作遇到错误', error)
            this.$message({
              message: '修改状态失败',
              type: 'error',
            })
          }
          this.getList()
        })
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep(::-webkit-scrollbar) {
  display: block !important;
}
::v-deep .el-dialog {
  width: 50% !important;
}
</style>
